package com.loan.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.domain.entity.SysUser;
import com.loan.common.core.domain.model.LoginUser;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.enums.PayCompanyEnum;
import com.loan.common.enums.SmsTemplateType;
import com.loan.common.helper.LoginHelper;
import com.loan.common.pay.hqpay.HQPayUtils;
import com.loan.common.pay.oddpay.VaUtils;
import com.loan.common.utils.BeanCopyUtils;
import com.loan.common.utils.DateUtils;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.*;
import com.loan.system.domain.req.AccountEntity;
import com.loan.system.domain.req.ConfigEntityReq;
import com.loan.system.domain.req.VaRepayEntity;
import com.loan.system.domain.vo.ExamineUserVo;
import com.loan.system.mapper.*;
import com.loan.system.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shiguang on 2022/9/7 14:57
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ApplyServiceImpl implements ApplyService {

    private final ApplyMapper applyMapper;

    private final SysUserMapper sysUserMapper;

    private final PayLogService payLogService;

    private final RepaymentLogService repaymentLogService;

    private final CompanyMapper companyMapper;

    private final PayConfigMapper payConfigMapper;

    private final UserService userService;

    private final UserBankService userBankService;

    private final BankService bankService;

    private final UserVaService uservaService;

    private final SmsTemplateService smsTemplateService;

    private final OverLogService overLogService;

    private final CollectionLogService collectionLogService;

    private final OverConfigService overConfigService;

    private final OverWeightService overWeightService;

    private final IncomeExpendDetailService incomeExpendDetailService;

    private final AppConfigService appConfigService;

    private final ExamineLogService examineLogService;

    private final CompanyDataMapper companyDataMapper;

    private final WithdrawalDataMapper withdrawalDataMapper;

    private final ChannelMapper channelMapper;

    private final CollectionOrderHandleService collectionOrderHandleService;

    @Override
    public TableDataInfo<ApplyEntity> selectPageList(ApplyEntity entity, PageQuery pageQuery, String overStatus, Integer applyType, String isDivide, String isRemark) {
        Page<ApplyEntity> page = new Page<>();
        if (StringUtils.isNotBlank(overStatus)) {
            Integer pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
            Integer pageSize = pageQuery.getPageSize();
            if (ObjectUtil.isNull(entity.getCustomerBy())) {
                entity.setCustomerBy(LoginHelper.getUserId());
            }
            List<ApplyEntity> list = applyMapper.selectPageList(entity, LoginHelper.getCompanyId(), overStatus,isRemark, pageNum, pageSize);
            int count = applyMapper.selectPageCount(entity, LoginHelper.getCompanyId(), overStatus,isRemark);
            page.setRecords(list);
            page.setTotal(count);
        } else {
            page = applyMapper.selectPageApplyList(pageQuery.build(), this.buildQueryWrapper(entity, applyType, isDivide,isRemark));
//            if (!CollectionUtils.isEmpty(page.getRecords())) {
//                for (ApplyEntity applyEntity : page.getRecords()) {
//                    //查询是否有逾期记录
//                    long count = overLogService.selectCountByUserIdAndCompanyId(applyEntity.getUserId(), applyEntity.getCompanyId());
//                    if (count > 0) {
//                        applyEntity.setOverStatus("1");
//                    } else {
//                        applyEntity.setOverStatus("0");
//                    }
//                }
//            }
        }
        return TableDataInfo.build(page);
    }

    /**
     * 获取待提现用户列表
     *
     * @param entity
     * @param pageQuery
     * @param overStatus
     * @param applyType
     * @param isDivide
     * @param isRemark
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPageWaitWithdrawallist(ApplyEntity entity, PageQuery pageQuery, String overStatus, Integer applyType, String isDivide, String isRemark) {
        Page<ApplyEntity> page = new Page<>();
        if (StringUtils.isNotBlank(overStatus)) {
            Long userId = LoginHelper.getUserId();
            SysUser sysUser = sysUserMapper.selectById(userId);
            if (sysUser.getPayCustomer().equals("1")) {
                entity.setCustomerBy(userId);
            }
            Integer pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
            Integer pageSize = pageQuery.getPageSize();
            List<ApplyEntity> list = applyMapper.selectPageWaitWithdrawallist(entity, LoginHelper.getCompanyId(), overStatus, isRemark, pageNum, pageSize);
            int count = applyMapper.selectWaitWithdrawalCount(entity, LoginHelper.getCompanyId(), overStatus, isRemark);
            page.setRecords(list);
            page.setTotal(count);
        } else {
            page = applyMapper.selectPageApplyList(pageQuery.build(), this.buildQueryWaitwithdrawalWrapper(entity, applyType, isDivide, isRemark));
        }
        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<ApplyEntity> selectPageFailList(Long userId, String orderSn, String userName, String userPhone, String status, String overStatus, String applyType, String createStartTime, String createEndTime, String examineStartTime, String examineEndTime, PageQuery pageQuery) {
        int pageSize = pageQuery.getPageSize();
        int pageNum = (pageQuery.getPageNum() - 1) * pageSize;
        List<ApplyEntity> list = applyMapper.selectFailList(userId, LoginHelper.getCompanyId(), orderSn, userName, userPhone, status, overStatus, applyType, createStartTime, createEndTime, examineStartTime, examineEndTime, pageNum, pageSize);
        int count = applyMapper.selectFailCount(userId, LoginHelper.getCompanyId(), orderSn, userName, userPhone, status, overStatus, applyType, createStartTime, createEndTime, examineStartTime, examineEndTime);
        Page<ApplyEntity> page = new Page<>();
        page.setRecords(list);
        page.setTotal(count);
        return TableDataInfo.build(page);
    }

    @Override
    public int recoveryApply(Long id) {
        ApplyEntity entity = applyMapper.selectById(id);
        UpdateWrapper<ApplyEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id)
                .set("one_examine_by", null)
                .set("one_examine_time", null)
                .set("two_examine_by", null)
                .set("two_examine_time", null)
                .set("recovery_time", new Date())
                .set("status", "0");
        return applyMapper.update(entity, wrapper);
    }

    @Override
    public void updateApplyWithdrawalStatus() {
        ConfigEntityReq config = appConfigService.getDetail();
        if (config.getWithdrawalExpireDay() > 0) {
            List<ApplyEntity> list = applyMapper.selectWithdrawalList(config.getWithdrawalExpireDay());
            for (ApplyEntity entity : list) {
                entity.setHitValue("0");
                entity.setHitRule("0");
                entity.setStatus("999");
                entity.setCancelTime(new Date());
                applyMapper.updateById(entity);
            }
        }
    }

    @Override
    public void robotApply() {
        List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>().eq("status", "999").eq("del_flag", "0"));
        for (ApplyEntity entity : list) {
            if (ObjectUtil.isNotNull(entity.getTwoExamineBy())) {
                entity.setStatus("2");
            } else {
                entity.setStatus("0");
            }
            entity.setRobotAuditTime(new Date());
            applyMapper.updateById(entity);
        }
    }

    /**
     * 放款成功列表
     *
     * @param
     * @param
     * @param entity
     * @param applyStartTime
     * @param applyEndTime
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPagePaySuccessList(ApplyEntity entity, String applyStartTime, String applyEndTime, PageQuery pageQuery) {
        Page<ApplyEntity> page = applyMapper.selectPageApplyList(pageQuery.build(), this.buildPaySuccessQueryWrapper(entity, applyStartTime, applyEndTime));
        for (ApplyEntity applyEntity : page.getRecords()) {
            PayLogEntity payLogEntity = payLogService.getByApplyId(applyEntity.getId());
            applyEntity.setPayLogEntity(payLogEntity);
        }
        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<ApplyEntity> selectPageWaitPayList(ApplyEntity entity, String applyStartTime, String applyEndTime, PageQuery pageQuery) {
        Page<ApplyEntity> page = applyMapper.selectPageApplyList(pageQuery.build(), this.buildWaitPayQueryWrapper(entity, applyStartTime, applyEndTime));
        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<ApplyEntity> selectPagePayFailsList(ApplyEntity entity, String applyStartTime, String applyEndTime, PageQuery pageQuery) {
        Page<ApplyEntity> page = applyMapper.selectPageApplyList(pageQuery.build(), this.buildPayFailQueryWrapper(entity, applyStartTime, applyEndTime));
        for (ApplyEntity applyEntity : page.getRecords()) {
            PayLogEntity payLogEntity = payLogService.getFailByApplyId(applyEntity.getId());
            applyEntity.setPayLogEntity(payLogEntity);
        }
        return TableDataInfo.build(page);
    }

    /**
     * 还款成功列表
     *
     * @param entity
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPageRepaySuccessList(ApplyEntity entity, PageQuery pageQuery) {
        Page<ApplyEntity> page = applyMapper.selectPageApplyList(pageQuery.build(), this.buildRepaySuccessQueryWrapper(entity));

        return TableDataInfo.build(page);
    }

    /**
     * 商户未分配数据统计
     */
    @Override
    public void companyUnassignedData() {
        String buildDate = DateUtils.getDate();
        //获取所有商户
        List<CompanyEntity> companyEntityList = companyMapper.selectList(new QueryWrapper<CompanyEntity>().eq("status", "0").eq("del_flag", "0"));
        for (CompanyEntity entity : companyEntityList) {
            //获取初审未分配订单
            long firstCount = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("company_id", entity.getId()).eq("status", "0").eq("del_flag", "0").isNull("one_examine_by"));
            //获取终审未分配订单
            long twoCount = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("company_id", entity.getId()).eq("status", "2").eq("del_flag", "0").isNull("two_examine_by"));
            //获取终审未审核订单
            long twoNoCount = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("company_id", entity.getId()).eq("status", "2").eq("del_flag", "0").isNotNull("two_examine_by"));
            //未分配待提现订单
            long waitWithdrawalCount = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("company_id", entity.getId()).eq("status", "4").eq("del_flag", "0").isNull("customer_by"));
            //当天放款笔数和金额
            Map<String, Object> map = applyMapper.selectPayMoneyAndPayNumByCompanyId(entity.getId());
            CompanyDataEntity companyDataEntity = companyDataMapper.selectOne(new QueryWrapper<CompanyDataEntity>().eq("build_date", buildDate).eq("company_id", entity.getId()));
            if (ObjectUtil.isNull(companyDataEntity)) {
                companyDataEntity = new CompanyDataEntity();
                companyDataEntity.setCreateDate(new Date());
            }
            companyDataEntity.setCompanyId(entity.getId());
            companyDataEntity.setCompanyName(entity.getName());
            companyDataEntity.setBuildDate(buildDate);
            companyDataEntity.setFirstNoNum(String.valueOf(firstCount));
            companyDataEntity.setTwoNoNum(String.valueOf(twoCount));
            companyDataEntity.setTwoNoExamineNum(String.valueOf(twoNoCount));
            companyDataEntity.setWaitWithdrawalNum(String.valueOf(waitWithdrawalCount));
            companyDataEntity.setPayNum(map.get("payNum").toString());
            companyDataEntity.setPayMoney(map.get("payMoney").toString());
            companyDataEntity.setUpdateDate(new Date());
            companyDataMapper.insertOrUpdate(companyDataEntity);
        }
    }

    /**
     * 提现监督报表统计
     */
    @Override
    public void withdrawalSuperviseData() {
        String buildDate = DateUtils.getDate();
        //获取所有商户
        List<CompanyEntity> companyEntityList = companyMapper.selectList(new QueryWrapper<CompanyEntity>().eq("status", "0").eq("del_flag", "0"));
        for (CompanyEntity entity : companyEntityList) {
            //获取该公司下所有的审核人员
            List<SysUser> sysUserList = sysUserMapper.selectList(new QueryWrapper<SysUser>().eq("company_id", entity.getId()).eq("examine", "1").eq("is_manage", "0").eq("status", "0").eq("del_flag", "0"));
            String examineNames = sysUserList.stream().map(SysUser::getUserName).collect(Collectors.joining(","));
            List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().eq("company_id", entity.getId()).eq("pay_customer", "1").eq("status", "0").eq("is_manage", "0").eq("del_flag", "0"));
            String customerNames = userList.stream().map(SysUser::getUserName).collect(Collectors.joining(","));
            //复审当天截至当前通过量
            Long towExamineNumber = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                    .eq("company_id", entity.getId())
                    .in("status", "4", "5", "6", "7")
                    .eq("del_flag", "0")
//                    .between("two_examine_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate()))
                    .between("second_audit_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate())));

            //获取当天分配案件
            Long num = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                    .eq("company_id", entity.getId())
                    .between("customer_create_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate())));
            //当天分配案件处理量
            Long num1 = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                    .eq("company_id", entity.getId())
                    .in("status", "5", "6", "7")
                    .eq("del_flag", "0")
                    .between("customer_create_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate())));
            //当天分配案件未处理量
            Long num4 = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                    .eq("company_id", entity.getId())
                    .eq("status", "4")
                    .eq("del_flag", "0")
                    .eq("is_follow_up", "0")
                    .between("customer_create_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate())));
            //当天处理案件
            Long num2 = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                    .eq("company_id", entity.getId())
                    .ne("status", "2")
                    .and(wrapper -> wrapper.between("customer_remark_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate()))
                            .or().between("cash_out_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate()))
                            .or().eq("is_follow_up", "2").between("follow_up_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate()))
                    )
            );
            //当天新案件提现量
            Long num3 = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                    .eq("company_id", entity.getId())
                    .in("status", "5", "6", "7")
                    .between("customer_create_time", DateUtils.toBeginDateByDay(DateUtils.getDate()), DateUtils.toEndDateByDay(DateUtils.getDate())));

            WithdrawalDataEntity withdrawalDataEntity = withdrawalDataMapper.selectOne(new QueryWrapper<WithdrawalDataEntity>()
                    .eq("build_date", buildDate)
                    .eq("company_id", entity.getId())
                    .last("limit 1")
            );
            if (ObjectUtil.isNull(withdrawalDataEntity)) {
                withdrawalDataEntity = new WithdrawalDataEntity();
                withdrawalDataEntity.setCreateTime(new Date());
            }
            withdrawalDataEntity.setBuildDate(buildDate);
            withdrawalDataEntity.setCompanyId(entity.getId());
            withdrawalDataEntity.setCompanyName(entity.getName());
            withdrawalDataEntity.setTwoExamineName(examineNames);
            withdrawalDataEntity.setCustomerName(customerNames);
            withdrawalDataEntity.setNewPassNum(Math.toIntExact(num1));
            withdrawalDataEntity.setNewFailNum(Math.toIntExact(num4));
            withdrawalDataEntity.setNewDayPassNum(Math.toIntExact(num2));
            withdrawalDataEntity.setNewDayWithdrawalNum(Math.toIntExact(num3));
            withdrawalDataEntity.setDayNum(Math.toIntExact(num));
            withdrawalDataEntity.setUpdateTime(new Date());
            withdrawalDataEntity.setTwoExamineNum(Math.toIntExact(towExamineNumber));
            withdrawalDataMapper.insertOrUpdate(withdrawalDataEntity);
        }
    }

    /**
     * 查询虚拟账户是否还款
     */
    @Override
    public void queryHqVaRepayLog() {
        List<UserVaEntity> list = uservaService.selectListByType("2");
        if (!CollectionUtils.isEmpty(list)) {
            for (UserVaEntity entity : list) {
                ApplyEntity applyEntity = applyMapper.selectById(entity.getApplyId());
                CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
                if (companyEntity.getPayType().equals("0")) {
                    //查询打款通道
                    if (companyEntity.getPayChannel() != null) {
                        PayConfigEntity payConfigEntity = payConfigMapper.selectById(companyEntity.getPayChannel());
                        if (payConfigEntity != null && payConfigEntity.getPayCompany().equals(PayCompanyEnum.HQ_PAY.getCode())) {
                            try {
                                String result = HQPayUtils.transaction(entity.getAccountNo(), DateUtils.getDate(), payConfigEntity.getHqpayToken());
                                JSONObject cardJsonResult = JSONObject.parseObject(result);
                                if (cardJsonResult.getBoolean("ok")) {
                                    String accounts = cardJsonResult.getString("data");
                                    List<VaRepayEntity> dataList = JSONObject.parseArray(accounts, VaRepayEntity.class);
                                    if (list.size() > 0) {
                                        for (VaRepayEntity vaRepay : dataList) {
                                            RepaymentLogEntity repaymentLogEntity = repaymentLogService.selectByTransRef(vaRepay.getTransRef());
                                            if (repaymentLogEntity == null) {
                                                repaymentLogEntity = new RepaymentLogEntity();
                                                repaymentLogEntity.setApplyId(applyEntity.getId());
                                                repaymentLogEntity.setUserId(applyEntity.getUserId());
                                                repaymentLogEntity.setRepaymentMoney(vaRepay.getAmount());
                                                repaymentLogEntity.setType("1");
                                                repaymentLogEntity.setStatus("2");
                                                repaymentLogEntity.setRepaymentTime(new Date());
                                                repaymentLogEntity.setCompanyId(applyEntity.getCompanyId());
                                                repaymentLogEntity.setCompanyType(null);
                                                repaymentLogEntity.setRemark("虚拟账户还款");
                                                repaymentLogEntity.setTransRef(vaRepay.getTransRef());
                                                repaymentLogEntity.setCollectionBy(applyEntity.getCollectionBy());
                                                repaymentLogService.insert(repaymentLogEntity);

                                                //判断是否平账
                                                applyEntity.setAlreadyRepayMoney(applyEntity.getAlreadyRepayMoney() + vaRepay.getAmount());
                                                if (applyEntity.getAlreadyRepayMoney() >= (applyEntity.getRealApplyMoney() + applyEntity.getOverMoney())) {
                                                    applyEntity.setStatus("7");
                                                    applyEntity.setAlreadyRepayTime(new Date());
                                                    applyMapper.updateById(applyEntity);
                                                    saveTwoExamineApply(applyEntity);
                                                }
                                            }
                                        }

                                    }

                                }
                            } catch (Exception e) {
                                log.error("虚拟账号查询异常:" + e.getMessage());
                            }
                        }
                    }
                }
            }
        }

    }

    /**
     * 添加跟进
     *
     * @param
     * @return
     */
    @Override
    public int saveFollowUpRemarkById(Long id, String followUpRemark) {
        ApplyEntity entity = applyMapper.selectById(id);
        entity.setFollowUpRemark(followUpRemark);
        entity.setFollowUpTime(new Date());
        entity.setIsFollowUp("2");
        return applyMapper.updateById(entity);
    }

    private Wrapper<ApplyEntity> buildRepaySuccessQueryWrapper(ApplyEntity entity) {
        Map<String, Object> params = entity.getParams();
        QueryWrapper<ApplyEntity> wrapper = Wrappers.query();

        wrapper.like(StringUtils.isNotBlank(entity.getUserName()), "a.user_name", entity.getUserName())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), "a.user_phone", entity.getUserPhone())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), "a.order_sn", entity.getOrderSn())
                .eq(ObjectUtil.isNotNull(entity.getCollectionBy()), "a.collection_by", entity.getCollectionBy())
                .eq(ObjectUtil.isNotNull(entity.getBalancerBy()), "a.balancer_by", entity.getBalancerBy())
                .eq(ObjectUtil.isNotNull(LoginHelper.getCompanyId()), "a.company_id", LoginHelper.getCompanyId())
                .eq(ObjectUtil.isNull(LoginHelper.getCompanyId()) && ObjectUtil.isNotNull(entity.getCompanyId()), "a.company_id", entity.getCompanyId())
                .in("a.status", "7")
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "a.already_repay_time", DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByDesc("a.id");
        return wrapper;
    }

    private Wrapper<ApplyEntity> buildPayFailQueryWrapper(ApplyEntity entity, String applyStartTime, String applyEndTime) {
        Map<String, Object> params = entity.getParams();
        QueryWrapper<ApplyEntity> wrapper = Wrappers.query();

        wrapper.like(StringUtils.isNotBlank(entity.getUserName()), "a.user_name", entity.getUserName())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), "a.user_phone", entity.getUserPhone())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), "a.order_sn", entity.getOrderSn())
                .eq(ObjectUtil.isNotNull(LoginHelper.getCompanyId()), "a.company_id", LoginHelper.getCompanyId())
                .in("a.status", "10")
                .between(StringUtils.isNotBlank(applyStartTime) && StringUtils.isNotBlank(applyEndTime), "a.apply_time",
                        DateUtils.toBeginDateByDay(params.get(applyStartTime)), DateUtils.toEndDateByDay(params.get(applyEndTime))
                )
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "a.create_time", DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByDesc("a.id");
        return wrapper;
    }

    private Wrapper<ApplyEntity> buildWaitPayQueryWrapper(ApplyEntity entity, String applyStartTime, String applyEndTime) {
        Map<String, Object> params = entity.getParams();
        QueryWrapper<ApplyEntity> wrapper = Wrappers.query();

        wrapper.like(StringUtils.isNotBlank(entity.getUserName()), "a.user_name", entity.getUserName())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), "a.user_phone", entity.getUserPhone())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), "a.order_sn", entity.getOrderSn())
                .eq(ObjectUtil.isNotNull(LoginHelper.getCompanyId()), "a.company_id", LoginHelper.getCompanyId())
                .eq("a.status", "5")
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "a.create_time", DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByDesc("a.id");
        return wrapper;
    }

    private Wrapper<ApplyEntity> buildPaySuccessQueryWrapper(ApplyEntity entity, String applyStartTime, String applyEndTime) {
        Map<String, Object> params = entity.getParams();
        QueryWrapper<ApplyEntity> wrapper = Wrappers.query();

        wrapper.like(StringUtils.isNotBlank(entity.getUserName()), "a.user_name", entity.getUserName())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), "a.user_phone", entity.getUserPhone())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), "a.order_sn", entity.getOrderSn())
                .eq(ObjectUtil.isNotNull(LoginHelper.getCompanyId()), "a.company_id", LoginHelper.getCompanyId())
                .in("a.status", "6", "7", "8")
                .between(StringUtils.isNotBlank(applyStartTime) && StringUtils.isNotBlank(applyEndTime), "a.apply_time",
                        DateUtils.toBeginDateByDay(applyStartTime), DateUtils.toEndDateByDay(applyEndTime)
                )
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "a.create_time", DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByDesc("a.id");
        return wrapper;
    }

    private Wrapper<ApplyEntity> buildQueryWaitwithdrawalWrapper(ApplyEntity entity, Integer applyType, String isDivide, String isRemark) {
        Map<String, Object> params = entity.getParams();
        QueryWrapper<ApplyEntity> wrapper = Wrappers.query();
        Long userId = LoginHelper.getUserId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (applyType != null) {
            applyType++;
        }
        if (sysUser.getIsManage().equals("0") && sysUser.getPayCustomer().equals("1")) {
            entity.setCustomerBy(userId);
        }
        wrapper.like(StringUtils.isNotBlank(entity.getUserName()), "a.user_name", entity.getUserName())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), "a.user_phone", entity.getUserPhone())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), "a.order_sn", entity.getOrderSn())
                .eq(ObjectUtil.isNotNull(entity.getUserId()), "a.user_id", entity.getUserId())
                .eq(ObjectUtil.isNotNull(entity.getApplyCycle()), "a.apply_cycle", entity.getApplyCycle())
                .eq(ObjectUtil.isNotNull(sysUser.getCompanyId()), "a.company_id", entity.getCompanyId())
                .eq(StringUtils.isNotBlank(entity.getStatus()), "a.status", entity.getStatus())
                .eq(ObjectUtil.isNotNull(entity.getCompanyId()), "a.company_id", entity.getCompanyId())
                .eq(ObjectUtil.isNotNull(entity.getOneExamineBy()), "a.one_examine_by", entity.getOneExamineBy())
                .eq(ObjectUtil.isNotNull(entity.getTwoExamineBy()), "a.two_examine_by", entity.getTwoExamineBy())
                .eq(ObjectUtil.isNotNull(entity.getCustomerBy()), "a.customer_by", entity.getCustomerBy())
                .isNotNull("a.customer_by")
                .eq(StringUtils.isNotBlank(isRemark) && isRemark.equals("0"), "a.customer_remark", "")
                .ne(StringUtils.isNotBlank(isRemark) && isRemark.equals("1"), "a.customer_remark", "")
                .isNull(StringUtils.isNotBlank(isDivide) && isDivide.equals("0"), "a.customer_by")
                .isNotNull(StringUtils.isNotBlank(isDivide) && isDivide.equals("1"), "a.customer_by")
                .eq(applyType != null, "apply_num", applyType)
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "a.customer_create_time", DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByDesc("a.id");
        return wrapper;
    }

    /**
     * 获取催收列表
     *
     * @param entity
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPageListOver(ApplyEntity entity,String isRemark, PageQuery pageQuery) {
        List<OverConfigEntity> overConfigList = new ArrayList<>();
        LoginUser loginUser = LoginHelper.getLoginUser();
        //获取最小的逾期日期
        int minDay = -1;
        if (loginUser.getCompanyId() != null) {
            minDay = overConfigService.selectByCompanyId(loginUser.getCompanyId());
        }
        Integer pageSize =  pageQuery.getPageSize();
        Integer pageNum = (pageQuery.getPageNum() - 1) * pageSize;
        Map<String, Object> params = entity.getParams();
        Object beginTime = params.get("beginTime");
        Object endTime = params.get("endTime");
        Long companyId = loginUser.getCompanyId()!= null ? loginUser.getCompanyId() : entity.getCompanyId();
        List<ApplyEntity> list = companyMapper.selectOverList(entity,isRemark, minDay, companyId, pageNum, beginTime, endTime, pageSize);
        int count = companyMapper.selectOverCount(entity,isRemark, minDay, beginTime, endTime, companyId);
        Page<ApplyEntity> page = new Page<>();
        page.setRecords(list);
        page.setSize(pageQuery.getPageSize());
        page.setTotal(count);
        page.setCurrent(pageQuery.getPageNum());
        for (ApplyEntity applyEntity : page.getRecords()) {
            CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
            applyEntity.setCompanyName(companyEntity.getName());
            CollectionLogEntity collectionLogEntity = collectionLogService.selectLastLogByApplyId(applyEntity.getId());
            if (ObjectUtil.isNotNull(collectionLogEntity)) {
                applyEntity.setOverDetails(collectionLogEntity.getDetail());
                applyEntity.setOverRemarkTime(collectionLogEntity.getCreateTime());
            }
            if (applyEntity.getOverDay() == 0) {
                Date startDate = DateUtils.parseDate(applyEntity.getRepaymentTime());
                long days = DateUtil.between(startDate, DateUtil.beginOfDay(new Date()), DateUnit.DAY);
                applyEntity.setOverDay((int) (-days));
            }
        }
        return TableDataInfo.build(page);
    }

    /**
     * 获取我的案件
     *
     * @param entity
     * @param overStatus
     * @param remark
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPageListMyOver(ApplyEntity entity, String overStatus, String remark, PageQuery pageQuery) {
        Map<String, Object> params = entity.getParams();
        LambdaQueryWrapper<ApplyEntity> lqw = new LambdaQueryWrapper<ApplyEntity>()
                .eq(ApplyEntity::getCollectionBy, LoginHelper.getUserId())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), ApplyEntity::getOrderSn, entity.getOrderSn())
                .like(StringUtils.isNotBlank(entity.getUserName()), ApplyEntity::getUserName, entity.getUserName())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), ApplyEntity::getUserPhone, entity.getUserPhone())
                .ne(StringUtils.isNotBlank(overStatus) && overStatus.equals("0"), ApplyEntity::getStatus, "7")
                .eq(StringUtils.isNotBlank(overStatus) && overStatus.equals("1"), ApplyEntity::getStatus, "7")
                .eq(ApplyEntity::getDelFlag, "0")
                .eq(StringUtils.isNotBlank(remark), ApplyEntity::getRemark, remark)
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        ApplyEntity::getRepaymentTime, params.get("beginTime"), params.get("endTime"))
                .orderByAsc(ApplyEntity::getRepaymentTime);
        Page<ApplyEntity> page = applyMapper.selectPage(pageQuery.build(), lqw);
//        Integer pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        for (ApplyEntity applyEntity : page.getRecords()) {
            CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
            applyEntity.setCompanyName(companyEntity.getName());
            CollectionLogEntity collectionLogEntity = collectionLogService.selectLastLogByApplyId(applyEntity.getId());
            if (ObjectUtil.isNotNull(collectionLogEntity)) {
                applyEntity.setOverDetails(collectionLogEntity.getDetail());
                applyEntity.setOverRemarkTime(collectionLogEntity.getCreateTime());
            }
            if (applyEntity.getOverDay() == 0) {
                Date startDate = DateUtils.parseDate(applyEntity.getRepaymentTime());
                long days = DateUtil.between(startDate, DateUtil.beginOfDay(new Date()), DateUnit.DAY);
                applyEntity.setOverDay((int) (-days));
            }
        }

        return TableDataInfo.build(page);
    }

    /**
     * 用户详情公债明细
     *
     * @param entity
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPageListUserInfo(ApplyEntity entity, PageQuery pageQuery) {
        Map<String, Object> params = entity.getParams();
        LambdaQueryWrapper<ApplyEntity> lqw = new LambdaQueryWrapper<ApplyEntity>()
                .eq(ApplyEntity::getUserId, entity.getUserId())
                .eq(ApplyEntity::getDelFlag, "0")
                .in(ApplyEntity::getStatus, "6", "7", "8")
                .orderByAsc(ApplyEntity::getRepaymentTime);
        Page<ApplyEntity> page = applyMapper.selectPage(pageQuery.build(), lqw);
        for (ApplyEntity applyEntity : page.getRecords()) {
            CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
            applyEntity.setCompanyName(companyEntity.getName());
        }
        return TableDataInfo.build(page);
    }

    /**
     * 获取初审订单列表
     *
     * @param entity
     * @param pageQuery
     * @param examineStatus
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPageListFirstExamine(ApplyEntity entity, PageQuery pageQuery, String examineStatus) {
        Map<String, Object> params = entity.getParams();
        LambdaQueryWrapper<ApplyEntity> lqw = new LambdaQueryWrapper<ApplyEntity>()
                .eq(ApplyEntity::getDelFlag, "0")
                .eq(ApplyEntity::getStatus, "0")
                .eq(ObjectUtil.isNotNull(LoginHelper.getCompanyId()), ApplyEntity::getCompanyId, LoginHelper.getCompanyId())
                .eq(StringUtils.isNotBlank(entity.getChannel()), ApplyEntity::getChannel, entity.getChannel())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), ApplyEntity::getOrderSn, entity.getOrderSn())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), ApplyEntity::getUserPhone, entity.getUserPhone())
                .isNull(StringUtils.isNotBlank(examineStatus) && examineStatus.equals("1"), ApplyEntity::getOneExamineBy)
                .isNotNull(StringUtils.isNotBlank(examineStatus) && examineStatus.equals("2"), ApplyEntity::getOneExamineBy)
                .eq(ObjectUtil.isNotNull(entity.getOneExamineBy()), ApplyEntity::getOneExamineBy, entity.getOneExamineBy())
                .eq(StringUtils.isNotBlank(entity.getIsFollowUp()), ApplyEntity::getIsFollowUp, entity.getIsFollowUp())
                .eq(StringUtils.isNotBlank(entity.getFirstApply()), ApplyEntity::getFirstApply, entity.getFirstApply())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        ApplyEntity::getOneExamineTime, DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByDesc(ApplyEntity::getId);
        Page<ApplyEntity> page = applyMapper.selectPage(pageQuery.build(), lqw);
        for (ApplyEntity applyEntity : page.getRecords()) {
            CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
            applyEntity.setCompanyName(companyEntity.getName());
            if (StringUtils.isNotBlank(applyEntity.getChannel())) {
                ChannelEntity channelEntity = channelMapper.selectOne(new QueryWrapper<ChannelEntity>().eq("code", applyEntity.getChannel()));
                if (ObjectUtil.isNotNull(channelEntity)) {
                    applyEntity.setChannelName(channelEntity.getName());
                }
            }
        }
        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<ApplyEntity> selectPageListFirst(ApplyEntity entity, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        Map<String, Object> params = entity.getParams();
        SysUser sysUser = sysUserMapper.selectById(userId);
//        LambdaQueryWrapper<ApplyEntity> lqw = new LambdaQueryWrapper<ApplyEntity>()
//                .eq(ApplyEntity::getDelFlag, "0")
//                .eq(ApplyEntity::getStatus, "0")
//                .eq(ApplyEntity::getOneExamineBy, userId)
//                .orderByDesc(ApplyEntity::getId);
//        Page<ApplyEntity> page = applyMapper.selectPage(pageQuery.build(), lqw);
//        for (ApplyEntity applyEntity : page.getRecords()) {
//            CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
//            applyEntity.setCompanyName(companyEntity.getName());
//        }
        entity.setCompanyId(LoginHelper.getCompanyId());
        if (ObjectUtil.isNull(entity.getOneExamineBy()) && sysUser.getIsManage().equals("0")) {
            entity.setOneExamineBy(userId);
        }
        int pageSize = pageQuery.getPageSize();
        int pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        List<ApplyEntity> list = new ArrayList<>();
        int count = 0;
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            list = applyMapper.selectPageListFirst(sysUser.getIsManage(), entity, DateUtils.parseDate(params.get("beginTime")), DateUtils.parseDate(params.get("endTime")), pageNum, pageSize);
            count = applyMapper.selectCountFirst(sysUser.getIsManage(), entity, DateUtils.parseDate(params.get("beginTime")), DateUtils.parseDate(params.get("endTime")));
        } else {
            list = applyMapper.selectPageListFirst(sysUser.getIsManage(), entity, null, null, pageNum, pageSize);
            count = applyMapper.selectCountFirst(sysUser.getIsManage(), entity, null, null);
        }
        Page<ApplyEntity> page = new Page<>();
        page.setRecords(list);
        page.setTotal(count);
        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<ApplyEntity> selectSearchList(String userName, String orderSn, String userPhone, String status, String overStatus, Integer applyType, Long companyId, PageQuery pageQuery) {
        Page<ApplyEntity> page = new Page<>();
        if (StringUtils.isNotBlank(orderSn) || StringUtils.isNotBlank(userPhone)
                || StringUtils.isNotBlank(status) || StringUtils.isNotBlank(overStatus)
                || ObjectUtil.isNotNull(applyType) || ObjectUtil.isNotNull(companyId)) {
            if (ObjectUtil.isNull(companyId)) {
                companyId = LoginHelper.getLoginUser().getCompanyId();
            }
            LambdaQueryWrapper<ApplyEntity> lqw = new LambdaQueryWrapper<ApplyEntity>()
                    .eq(StringUtils.isNotBlank(status), ApplyEntity::getStatus, status)
                    .eq(ObjectUtil.isNotNull(companyId), ApplyEntity::getCompanyId, companyId)
                    .like(StringUtils.isNotBlank(orderSn), ApplyEntity::getOrderSn, orderSn)
                    .like(StringUtils.isNotBlank(userName), ApplyEntity::getUserName, userName)
                    .like(StringUtils.isNotBlank(userPhone), ApplyEntity::getUserPhone, userPhone)
                    .eq(StringUtils.isNotBlank(overStatus) && overStatus.equals("1"), ApplyEntity::getStatus, "8")
                    .ne(StringUtils.isNotBlank(overStatus) && overStatus.equals("0"), ApplyEntity::getStatus, "8")
                    .in(ObjectUtil.isNotNull(applyType), ApplyEntity::getStatus, "6", "7", "8")
                    .inSql(ObjectUtil.isNotNull(companyId) && ObjectUtil.isNotNull(applyType) && applyType == 0, ApplyEntity::getUserId, "select user_id from vn_user_apply where status in ('6','7','8') and company_id = " + companyId + " group by user_id having count(user_id) = 1")
                    .inSql(ObjectUtil.isNotNull(companyId) && ObjectUtil.isNotNull(applyType) && applyType == 1, ApplyEntity::getUserId, "select user_id from vn_user_apply where status in ('6','7','8') and company_id = " + companyId + " group by user_id having count(user_id) = 2")
                    .inSql(ObjectUtil.isNotNull(companyId) && ObjectUtil.isNotNull(applyType) && applyType == 2, ApplyEntity::getUserId, "select user_id from vn_user_apply where status in ('6','7','8') and company_id = " + companyId + " group by user_id having count(user_id) = 3")
                    .inSql(ObjectUtil.isNotNull(companyId) && ObjectUtil.isNotNull(applyType) && applyType == 3, ApplyEntity::getUserId, "select user_id from vn_user_apply where status in ('6','7','8') and company_id = " + companyId + " group by user_id having count(user_id) = 4")
                    .inSql(ObjectUtil.isNotNull(companyId) && ObjectUtil.isNotNull(applyType) && applyType == 4, ApplyEntity::getUserId, "select user_id from vn_user_apply where status in ('6','7','8') and company_id = " + companyId + " group by user_id having count(user_id) = 5")
                    .inSql(ObjectUtil.isNotNull(companyId) && ObjectUtil.isNotNull(applyType) && applyType == 5, ApplyEntity::getUserId, "select user_id from vn_user_apply where status in ('6','7','8') and company_id = " + companyId + " group by user_id having count(user_id) = 6")
                    .inSql(ObjectUtil.isNotNull(companyId) && ObjectUtil.isNotNull(applyType) && applyType == 6, ApplyEntity::getUserId, "select user_id from vn_user_apply where status in ('6','7','8') and company_id = " + companyId + " group by user_id having count(user_id) = 7")
                    .inSql(ObjectUtil.isNotNull(companyId) && ObjectUtil.isNotNull(applyType) && applyType == 7, ApplyEntity::getUserId, "select user_id from vn_user_apply where status in ('6','7','8') and company_id = " + companyId + " group by user_id having count(user_id) = 8")
                    .orderByDesc(ApplyEntity::getId);
            page = applyMapper.selectPage(pageQuery.build(), lqw);
        }
        for (ApplyEntity entity : page.getRecords()) {
            CompanyEntity companyEntity = companyMapper.selectById(entity.getCompanyId());
            entity.setCompanyName(companyEntity.getName());
        }
        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<ApplyEntity> selectPageListOverRepayment(ApplyEntity entity, PageQuery pageQuery) {
        Map<String, Object> params = entity.getParams();
        String beginTime = null;
        String endTime = null;
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            beginTime = params.get("beginTime").toString();
            endTime = params.get("beginTime").toString();
        }
        Integer pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        SysUser sysUser = sysUserMapper.selectById(LoginHelper.getUserId());
        List<ApplyEntity> list = new ArrayList<>();
        int count = 0;
        if (sysUser.getIsManage().equals("0")) {
            list = applyMapper.selectPageListOverRepayment(entity.getOrderSn(), entity.getUserName(), entity.getUserPhone(),
                    beginTime, endTime, LoginHelper.getUserId(),LoginHelper.getCompanyId(), pageNum, pageQuery.getPageSize());
            count = applyMapper.selectCountOverRepayment(entity.getOrderSn(), entity.getUserName(), entity.getUserPhone(),
                    beginTime, endTime, LoginHelper.getUserId(),LoginHelper.getCompanyId());
        } else {
            list = applyMapper.selectPageListOverRepayment(entity.getOrderSn(), entity.getUserName(), entity.getUserPhone(),
                    beginTime, endTime, null,LoginHelper.getCompanyId(), pageNum, pageQuery.getPageSize());
            count = applyMapper.selectCountOverRepayment(entity.getOrderSn(), entity.getUserName(), entity.getUserPhone(),
                    beginTime, endTime, null,LoginHelper.getCompanyId());
        }
        Page<ApplyEntity> page = new Page<>();
        page.setRecords(list);
        page.setTotal(count);
        return TableDataInfo.build(page);
    }

    /**
     * 获取待还款订单
     *
     * @param entity
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPageListWaiPayment(ApplyEntity entity, PageQuery pageQuery) {
        Map<String, Object> params = entity.getParams();
        LambdaQueryWrapper<ApplyEntity> lqw = new LambdaQueryWrapper<ApplyEntity>()
                .eq(ApplyEntity::getDelFlag, "0")
                .in(ApplyEntity::getStatus, "6", "8")
                .eq(ObjectUtil.isNotNull(LoginHelper.getLoginUser().getCompanyId()), ApplyEntity::getCompanyId, LoginHelper.getLoginUser().getCompanyId())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), ApplyEntity::getOrderSn, entity.getOrderSn())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), ApplyEntity::getUserPhone, entity.getUserPhone())
                .like(StringUtils.isNotBlank(entity.getUserName()), ApplyEntity::getUserName, entity.getUserName())
                .like(StringUtils.isNotBlank(entity.getIdCardNumber()), ApplyEntity::getIdCardNumber, entity.getIdCardNumber())
                .like(StringUtils.isNotBlank(entity.getBankCardNo()), ApplyEntity::getBankCardNo, entity.getBankCardNo())
                .eq(ObjectUtil.isNotNull(entity.getOneExamineBy()), ApplyEntity::getOneExamineBy, entity.getOneExamineBy())
                .eq(ObjectUtil.isNotNull(entity.getTwoExamineBy()), ApplyEntity::getTwoExamineBy, entity.getTwoExamineBy())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        ApplyEntity::getApplyTime, DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByAsc(ApplyEntity::getRepaymentTime);
        Page<ApplyEntity> page = applyMapper.selectPage(pageQuery.build(), lqw);
        for (ApplyEntity applyEntity : page.getRecords()) {
            CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
            applyEntity.setCompanyName(companyEntity.getName());
        }
        return TableDataInfo.build(page);
    }

    /**
     * 获取终审订单列表
     *
     * @param entity
     * @param pageQuery
     * @param examineStatus
     * @return
     */
    @Override
    public TableDataInfo<ApplyEntity> selectPageListTwoExamine(ApplyEntity entity, PageQuery pageQuery, String examineStatus) {
        Map<String, Object> params = entity.getParams();
        LambdaQueryWrapper<ApplyEntity> lqw = new LambdaQueryWrapper<ApplyEntity>()
                .eq(ApplyEntity::getDelFlag, "0")
                .eq(ApplyEntity::getStatus, "2")
                .eq(ObjectUtil.isNotNull(LoginHelper.getLoginUser().getCompanyId()), ApplyEntity::getCompanyId, LoginHelper.getLoginUser().getCompanyId())
                .eq(StringUtils.isNotBlank(entity.getChannel()), ApplyEntity::getChannel, entity.getChannel())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), ApplyEntity::getOrderSn, entity.getOrderSn())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), ApplyEntity::getUserPhone, entity.getUserPhone())
                .isNull(StringUtils.isNotBlank(examineStatus) && examineStatus.equals("1"), ApplyEntity::getTwoExamineBy)
                .isNotNull(StringUtils.isNotBlank(examineStatus) && examineStatus.equals("2"), ApplyEntity::getTwoExamineBy)
                .eq(StringUtils.isNotBlank(entity.getIsFollowUp()), ApplyEntity::getIsFollowUp, entity.getIsFollowUp())
                .eq(ObjectUtil.isNotNull(entity.getTwoExamineBy()), ApplyEntity::getTwoExamineBy, entity.getTwoExamineBy())
                .eq(StringUtils.isNotBlank(entity.getFirstApply()), ApplyEntity::getFirstApply, entity.getFirstApply())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        ApplyEntity::getTwoExamineTime, DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByDesc(ApplyEntity::getId);
        Page<ApplyEntity> page = applyMapper.selectPage(pageQuery.build(), lqw);
        for (ApplyEntity applyEntity : page.getRecords()) {
            CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
            applyEntity.setCompanyName(companyEntity.getName());
            if (StringUtils.isNotBlank(applyEntity.getChannel())) {
                ChannelEntity channelEntity = channelMapper.selectOne(new QueryWrapper<ChannelEntity>().eq("code", applyEntity.getChannel()));
                if (ObjectUtil.isNotNull(channelEntity)) {
                    applyEntity.setChannelName(channelEntity.getName());
                }
            }
        }
        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<ApplyEntity> selectPageListTwo(ApplyEntity entity, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        Map<String, Object> params = entity.getParams();
        entity.setCompanyId(LoginHelper.getCompanyId());
        if (Objects.isNull(entity.getTwoExamineBy()) && sysUser.getIsManage().equals("0")) {
            entity.setTwoExamineBy(userId);
        }
        int pageSize = pageQuery.getPageSize();
        int pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        List<ApplyEntity> list = new ArrayList<>();
        int count = 0;
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            list = applyMapper.selectPageListTwo(sysUser.getIsManage(), entity, DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")), pageNum, pageSize);
            count = applyMapper.selectCountTwo(sysUser.getIsManage(), entity, DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")));
        } else {
            list = applyMapper.selectPageListTwo(sysUser.getIsManage(), entity, null, null, pageNum, pageSize);
            count = applyMapper.selectCountTwo(sysUser.getIsManage(), entity, null, null);
        }
        Page<ApplyEntity> page = new Page<>();
        page.setRecords(list);
        page.setTotal(count);
        return TableDataInfo.build(page);
    }

    /**
     * 催收订单分配
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateApplyCollectionByJobHandle() {
        //获取所有的小平台
        List<CompanyEntity> companyList = companyMapper.selectList();
        //根据公司获取该公司下的催收配置
        for (CompanyEntity companyEntity : companyList) {
            List<OverConfigEntity> overConfigEntityList = overConfigService.selectList(companyEntity.getId());
            //根据配置查找对应的催收人 和分配权重 分配订单
            for (OverConfigEntity overConfigEntity : overConfigEntityList) {
                //查询该配置下的订单
                List<OverWeightEntity> overWeightList = overWeightService.selectListByOverId(overConfigEntity.getId());
                List<Long> userIds = overWeightList.stream().map(OverWeightEntity::getUserId).collect(Collectors.toList());
                Map<Long, Integer> map = overWeightList.stream().collect(Collectors.toMap(OverWeightEntity::getUserId, OverWeightEntity::getWeight, (key1, key2) -> key1));
                if (!CollectionUtils.isEmpty(userIds)) {
                    List<ApplyEntity> applyList = applyMapper.selectOverApplyList(overConfigEntity.getMinDay(), overConfigEntity.getMaxDay(), userIds, companyEntity.getId());
                    for (ApplyEntity entity : applyList) {
                        Long userId = StringUtils.selectNode(map);
                        entity.setCollectionBy(userId);
                        entity.setOverExamineTime(new Date());
                        applyMapper.updateById(entity);
                        //增减逾期分配记录
                        collectionOrderHandleService.save(entity, overConfigEntity, true);
                    }
                }
            }
        }
    }

    @Override
    public List<ApplyEntity> listApplyCompany(ApplyEntity entity) {
        return applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                .eq("user_id", entity.getUserId())
                .eq(LoginHelper.getLoginUser().getCompanyId() != null, "company_id", LoginHelper.getLoginUser().getCompanyId())
                .orderByDesc("id")
        );
    }

    @Override
    public ApplyEntity getInfo(Long id, Long userId) {
        ApplyEntity applyEntity = applyMapper.selectById(id);
        if (applyEntity == null || !applyEntity.getUserId().equals(userId)) {
            return null;
        }
        //判断该用户当前是否有逾期的订单
        Long count = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", userId).eq("status", "8").eq("del_flag", "0"));
        if (count > 0) {
            applyEntity.setIsOverOrders(true);
        }
        //判断用户30天内是否有提前四天还款的订单
        List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                .eq("user_id", userId)
                .eq("status", "7")
                .ge("already_repay_time", DateUtils.addDays(new Date(), -30)));
        for (ApplyEntity entity : list) {
            if (DateUtils.differentDaysByMillisecond(entity.getAlreadyRepayTime(), DateUtils.parseDate(entity.getRepaymentTime())) >= 4) {
                applyEntity.setIsBeforeRepayment(true);
                break;
            }
        }
        return applyEntity;
    }

    @Override
    public TableDataInfo<RepaymentLogEntity> selectRepaymentLogList(RepaymentLogEntity entity, PageQuery pageQuery) {
        Page<RepaymentLogEntity> page = repaymentLogService.selectRepaymentLogList(entity, pageQuery);
        return TableDataInfo.build(page);
    }

    @Override
    public int revokeRepaymentLog(String id) {
        return repaymentLogService.revokeRepaymentLogById(id);
    }

    @Override
    public List<ExamineUserVo> listExamineUser() {
        if (LoginHelper.isAdmin()) {
            List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().eq("examine", "1").eq("del_flag", "0").orderByDesc("user_id"));
            return BeanCopyUtils.copyList(userList, ExamineUserVo.class);
        }
        SysUser sysUser = sysUserMapper.selectById(LoginHelper.getUserId());
        List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>()
                .eq("company_id", sysUser.getCompanyId())
                .eq(sysUser.getIsManage().equals("0"), "user_id", sysUser.getUserId())
                .eq("examine", "1")
                .eq("del_flag", "0")
                .orderByDesc("user_id"));
        return BeanCopyUtils.copyList(userList, ExamineUserVo.class);
    }

    @Override
    public List<ExamineUserVo> listCollectionUser() {
        if (LoginHelper.isAdmin()) {
            List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().eq("collection", "1").eq("del_flag", "0").orderByDesc("user_id"));
            return BeanCopyUtils.copyList(userList, ExamineUserVo.class);
        }
        SysUser sysUser = sysUserMapper.selectById(LoginHelper.getUserId());
        List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>()
                .eq("company_id", sysUser.getCompanyId())
                .eq("collection", "1")
                .eq("del_flag", "0")
                .orderByDesc("user_id"));
        return BeanCopyUtils.copyList(userList, ExamineUserVo.class);

    }

    @Override
    public List<ApplyEntity> applyLogList(Long userId) {
        return applyMapper.applyLogList(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateApplyOneExamineBy(Long oneExamineBy, String ids) {
        List<Long> list = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        return applyMapper.updateApplyOneExamineBy(oneExamineBy, list);
    }

    /**
     * 催收订单指定分配
     *
     * @param collectionBy
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateApplyCollectionBy(Long collectionBy, String ids) {
        List<Long> list = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        for (Long id : list) {
            ApplyEntity applyEntity = applyMapper.selectById(id);
            applyEntity.setCollectionBy(collectionBy);
            applyEntity.setOverExamineTime(new Date());
            collectionOrderHandleService.saveByApply(applyEntity);
        }

        return applyMapper.updateApplyCollectionBy(collectionBy, list);
    }

    /**
     * 本金收回率
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public List<Map<String, Object>> selectPageCapitalBack(String beginTime, String endTime) {
        Long companyId = LoginHelper.getCompanyId();
        List<Map<String, Object>> list = applyMapper.selectPageCapitalBack(companyId, beginTime, endTime);
        //获取大盘数据
        Map<String, Object> map = applyMapper.selectMarket(beginTime, endTime);
        for (Map<String, Object> m : list) {
            //实际放款
            m.put("dApplyMoney", map.get("money"));
            //实际还款
            m.put("dRepayMoney", map.get("money1"));
            //合同金额
            m.put("dMoney", map.get("money2"));
        }
        return list;
    }

    /**
     * 商户报表
     *
     * @param beginTime
     * @param endTime
     * @param companyId
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<Map<String, Object>> selectCompanyDataList(String beginTime, String endTime, Long companyId, PageQuery pageQuery) {


        Integer pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        Integer pageSize = pageQuery.getPageSize();
        companyId = ObjectUtil.isNotNull(LoginHelper.getCompanyId()) ? LoginHelper.getCompanyId() : companyId;
        List<Map<String, Object>> list = applyMapper.selectCompanyDataList(beginTime, endTime, companyId, pageNum, pageSize);
        int count = applyMapper.selectCompanyDataCount(beginTime, endTime, companyId);
        Page<Map<String, Object>> page = new Page<>();
        page.setRecords(list);
        page.setTotal(count);
        return TableDataInfo.build(page);
    }

    /**
     * 提现数据统计
     *
     * @param beginTime
     * @param endTime
     * @param customerId
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<Map<String, Object>> selectPayDataList(String beginTime, String endTime, Long customerId, PageQuery pageQuery) {
        Long companyId = LoginHelper.getCompanyId();
        Integer pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        Integer pageSize = pageQuery.getPageSize();
        List<Map<String, Object>> list = applyMapper.selectPayDataList(companyId, beginTime, endTime, customerId, pageNum, pageSize);
        int count = applyMapper.selectPayDataCount(companyId, beginTime, endTime, customerId);
        Page<Map<String, Object>> page = new Page<>();
        page.setRecords(list);
        page.setTotal(count);
        return TableDataInfo.build(page);
    }

    /**
     * 提现报表汇总
     *
     * @param beginTime
     * @param endTime
     * @param customerId
     * @return
     */
    @Override
    public Map<String, Object> selectPayDataTotal(String beginTime, String endTime, Long customerId) {

        return applyMapper.selectPayDataTotal(beginTime, endTime, customerId, LoginHelper.getCompanyId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateApplyTwoExamineBy(Long twoExamineBy, String ids) {
        List<Long> list = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        return applyMapper.updateApplyTwoExamineBy(twoExamineBy, list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateApplyCutomerBy(Long customerBy, String ids) {
        List<Long> list = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        return applyMapper.updateApplyCutomerBy(customerBy, list);
    }

    /**
     * 打款
     *
     * @param applyId
     * @param type
     * @param bankOrderNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int payApply(Long applyId, String type, String bankOrderNo) {
        int count = 0;
        ApplyEntity applyEntity = applyMapper.selectById(applyId);
        UserBankEntity userBank = userBankService.getUserBank(applyEntity.getUserId());
        CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
        BankEntity bankEntity = bankService.selectById(userBank.getBankId());
        if (type.equals("0")) {
            //线下打款
            //修改订单记录

            //根据周期计算应还日期
            Date date = DateUtils.addDays(new Date(), applyEntity.getApplyCycle() - 1);
            applyEntity.setRepaymentTime(DateUtils.parseDateToStr("yyyy-MM-dd", date));
            applyEntity.setApplyTime(new Date());
            applyEntity.setStatus("6");
            applyEntity.setBankCardNo(userBank.getBankNo());
            applyEntity.setSimpleName(userBank.getSimpleName());
            //判断是否是白户  白户定义  该用户没有还款记录就是白户
            Long num = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", applyEntity.getUserId()).in("status", "7"));
            long systemNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().in("status", "6", "7", "8").eq("user_id", applyEntity.getUserId()));
            long agentNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", applyEntity.getUserId()).in("status", "6", "7", "8").eq("company_id", applyEntity.getCompanyId()));
            applyEntity.setAgentBorrowLevel(agentNum == 0 ? 1 : (int) (agentNum + 1));
            applyEntity.setSystemBorrowLevel(systemNum == 0 ? 1 : (int) (systemNum + 1));
            if (num == 0) {
                applyEntity.setWhiteUser("1");
            } else {
                applyEntity.setWhiteUser("0");
            }
            count = applyMapper.updateById(applyEntity);

            Map params = new HashMap();
            params.put("companyName", "(" + companyEntity.getName() + ")");
            params.put("bankName", bankEntity.getSimpleName());
            smsTemplateService.sendSms(StringUtils.checkPhone(applyEntity.getUserPhone()), SmsTemplateType.PAY_SUCCESS.getCode(), params);
            //添加打款记录
            payLogService.saveLog(applyEntity, type, bankOrderNo);

        } else if (type.equals("1")) {
            //线上打款
            //修改订单状态为待打款状态
            applyEntity.setStatus("5");
            applyMapper.updateById(applyEntity);
            count = 1;
        }
        return count;
    }

    /**
     * 如果是白户添加到收支统计
     *
     * @param applyEntity
     */
    private void saveWhiteOrder(ApplyEntity applyEntity) {
        //判断该用户在该平台是否是第一次放款
        Long count = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                .eq("user_id", applyEntity.getUserId())
                .eq("company_id", applyEntity.getCompanyId())
                .in("status", "6", "7", "8", "9")
                .ne("id", applyEntity.getId())
        );
        if (count == 0) {
            //添加白户数到收支统计
            String buildDate = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
            IncomeExpendDetailEntity entity = incomeExpendDetailService.selectByCompanyIdAndDate(applyEntity.getCompanyId(), buildDate);
            if (entity != null) {
                entity.setWhiteNum(entity.getWhiteNum() + 1);
                entity.setWhiteOrderNum(entity.getWhiteOrderNum() + 1);
                incomeExpendDetailService.updateWhiteById(entity);
            } else {
                entity = new IncomeExpendDetailEntity();
                entity.setWhiteNum(1);
                entity.setWhiteOrderNum(1);
                entity.setCompanyId(applyEntity.getCompanyId());
                entity.setBuildDate(buildDate);
                incomeExpendDetailService.save(entity);
            }
        }
    }

    @Override
    public void pay() {

        //查询开启了线上打款且还没打款的订单
        List<CompanyEntity> companyList = companyMapper.selectList(new QueryWrapper<CompanyEntity>()
                .eq("status", "0")
                .eq("del_flag", "0")
                .eq("pay_type", "0")
                .isNotNull("pay_channel")
        );
        if (!CollectionUtils.isEmpty(companyList)) {
            List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                    .eq("status", "5")
                    .eq("del_flag", "0")
            );
            if (!CollectionUtils.isEmpty(list)) {
                for (ApplyEntity entity : list) {
                    payApplyNew(entity);
                }
            }
        }

    }

    @Override
    public void queryPayOrderApply() {
        List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                .eq("status", "9")
                .eq("del_flag", "0")
        );
        if (!CollectionUtils.isEmpty(list)) {
            for (ApplyEntity entity : list) {
                queryPayOrderStatus(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int closeApply(String ids) {
        List<Long> list = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        return applyMapper.deleteBatchIds(list);
    }

    @Override
    public String updateApplyByMsg(HttpServletRequest request) {
        if (request.getParameter("retCode").equals("0000")) {
            String retInfo = request.getParameter("retInfo");
            String[] strs = retInfo.split("___");
            String accountNo = strs[0];
            String accountName = strs[1];
            UserVaEntity userVaEntity = uservaService.selectByNoAndName(accountNo, accountName);
            if (userVaEntity != null) {
                String amount = request.getParameter("amount");
                ApplyEntity applyEntity = applyMapper.selectVoById(userVaEntity.getId());
                applyEntity.setAlreadyRepayMoney(applyEntity.getAlreadyRepayMoney() + Integer.valueOf(amount));
                if (applyEntity.getAlreadyRepayMoney() >= applyEntity.getRealApplyMoney() + applyEntity.getInterestMoney() + applyEntity.getOverMoney()) {
                    //还款总金额大于等于应还金额
                    applyEntity.setStatus("7");
                    applyEntity.setAlreadyRepayTime(new Date());
                    applyMapper.updateById(applyEntity);
                    //增加还款记录
                    repaymentLogService.savePaymentLog(applyEntity, "1", Integer.valueOf(amount), PayCompanyEnum.ODD_PAY.getCode(), null);
                    saveTwoExamineApply(applyEntity);
                } else {
                    applyMapper.updateById(applyEntity);
                    //增加还款记录
                    repaymentLogService.savePaymentLog(applyEntity, "1", Integer.valueOf(amount), PayCompanyEnum.ODD_PAY.getCode(), null);
                }
                CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
                Map map = new HashMap();
                map.put("companyName", "(" + companyEntity.getName() + ")");
                map.put("money", amount);
                smsTemplateService.sendSms(StringUtils.checkPhone(applyEntity.getUserPhone()), SmsTemplateType.PAYMENT_SUCCESS.getCode(), map);
                return "success";
            }
        }
        log.error("验证失败");
        return "fail";

    }

    @Override
    public void checkPaymentData(JSONObject data, String signature) {
        log.info("hqpay 回调数据:" + data.toJSONString());
        log.info("验签数据:" + signature);
        String account = data.getString("numberOfBeneficiary");
        Integer amount = data.getInteger("amount");
        log.info("cardId:{},amount:{}", account, amount);
        UserVaEntity userVaEntity = uservaService.selectByCardId(account);
        if (userVaEntity == null) {
            String bank = data.getString("account");
            log.info("account:{},amount:{},bank:{}", account, amount, bank);
            userVaEntity = uservaService.selectByBank(account);
        }
        if (userVaEntity != null) {
            String remark = data.getString("description");
            PayConfigEntity payConfigEntity = payConfigMapper.selectById(userVaEntity.getPayConfigId());
            String publicKey = payConfigEntity.getPublicKey();
//            boolean sign = HQPayUtils.verifySign(publicKey, data.toJSONString(), signature);
//            if (sign) {
            ApplyEntity applyEntity = applyMapper.selectById(userVaEntity.getApplyId());
            applyEntity.setAlreadyRepayMoney(applyEntity.getAlreadyRepayMoney() + amount);
            if (applyEntity.getAlreadyRepayMoney() >= applyEntity.getRealApplyMoney() + applyEntity.getInterestMoney() + applyEntity.getOverMoney()) {
                //还款总金额大于等于应还金额
                applyEntity.setStatus("7");
                applyEntity.setAlreadyRepayTime(new Date());
                applyMapper.updateById(applyEntity);
                //增加还款记录
                repaymentLogService.savePaymentLog(applyEntity, "1", amount, PayCompanyEnum.HQ_PAY.getCode(), remark);
                saveTwoExamineApply(applyEntity);
                CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
                Map map = new HashMap();
                map.put("companyName", "(" + companyEntity.getName() + ")");
                map.put("money", amount);
                smsTemplateService.sendSms(StringUtils.checkPhone(applyEntity.getUserPhone()), SmsTemplateType.PAYMENT_SUCCESS.getCode(), map);
            } else {
                applyMapper.updateById(applyEntity);
                //增加还款记录
                repaymentLogService.savePaymentLog(applyEntity, "1", amount, PayCompanyEnum.ODD_PAY.getCode(), remark);
            }
            //判断是否绑定催收用户
            if (ObjectUtil.isNotNull(applyEntity.getCollectionBy())) {
                CollectionOrderHandleEntity collectionOrderHandleEntity = collectionOrderHandleService.selectByApply(applyEntity);
                if (ObjectUtil.isNotNull(collectionOrderHandleEntity)) {
                    collectionOrderHandleEntity.setCallbackAmount(collectionOrderHandleEntity.getCallbackAmount() + amount);
                    if (applyEntity.getStatus().equals("7")) {
                        collectionOrderHandleEntity.setStatus("success");
                    }
                    collectionOrderHandleEntity.setUpdateTime(new Date());
                    collectionOrderHandleService.update(collectionOrderHandleEntity);
                }
            }
//            } else {
//                log.error("验签失败");
//                repaymentLogService.savePaymentLogFail(null, "1", amount, PayCompanyEnum.HQ_PAY.getCode(),data.toJSONString() + ";signature=" + signature);
//                throw new ServiceException("验签失败");
//            }
        } else {
            //判断是否通过卡号还款
            //增加还款记录
            repaymentLogService.savePaymentLogFail(null, "1", amount, PayCompanyEnum.HQ_PAY.getCode(), data.toJSONString());
        }
    }

    /**
     * 到期前一天
     */
    @Override
    public void sendPaymentBeforeDay() {
        Date date = DateUtils.addDays(new Date(), 1);

        List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                .eq("status", "6")
                .eq("del_flag", "0")
                .eq("repayment_time", DateUtils.parseDateToStr("yyyy-MM-dd", date))
        );
        if (CollectionUtil.isNotEmpty(list)) {
            //发送短信
            for (ApplyEntity entity : list) {
                CompanyEntity companyEntity = companyMapper.selectById(entity.getCompanyId());
                Map map = new HashMap();
                map.put("companyName", "(" + companyEntity.getName() + ")");
                map.put("money", entity.getRealApplyMoney());
                smsTemplateService.sendSms(StringUtils.checkPhone(entity.getUserPhone()), SmsTemplateType.EXPIRE_DAY_BEFORE_ONE.getCode(), map);
            }
        }
    }

    /**
     * 到期当天
     */
    @Override
    public void sendPaymentDay() {
        List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                .eq("status", "6")
                .eq("del_flag", "0")
                .eq("repayment_time", DateUtils.parseDateToStr("yyyy-MM-dd", new Date()))
        );
        if (CollectionUtil.isNotEmpty(list)) {
            //发送短信
            for (ApplyEntity entity : list) {
                CompanyEntity companyEntity = companyMapper.selectById(entity.getCompanyId());
                Map map = new HashMap();
                map.put("companyName", "(" + companyEntity.getName() + ")");
                map.put("money", entity.getRealApplyMoney());
                smsTemplateService.sendSms(StringUtils.checkPhone(entity.getUserPhone()), SmsTemplateType.EXPIRE_DAY_BEFORE.getCode(), map);
            }
        }
    }

    /**
     * 逾期
     */
    @Override
    public void sendPaymentOverDay() {
        Date date = DateUtils.addDays(new Date(), -1);
        List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                .eq("status", "8")
                .eq("del_flag", "0")
                .eq("repayment_time", DateUtils.parseDateToStr("yyyy-MM-dd", date))
        );
        if (CollectionUtil.isNotEmpty(list)) {
            //发送短信
            for (ApplyEntity entity : list) {
                Integer money = entity.getRealApplyMoney() + entity.getInterestMoney() + entity.getOverMoney();
                CompanyEntity companyEntity = companyMapper.selectById(entity.getCompanyId());
                Map map = new HashMap();
                map.put("companyName", "(" + companyEntity.getName() + ")");
                map.put("money", money);
                smsTemplateService.sendSms(StringUtils.checkPhone(entity.getUserPhone()), SmsTemplateType.OVERDUE_ONE_DAY.getCode(), map);
            }
        }
    }

    @Override
    public void updateOverApply() {
        List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                .in("status", "6", "8")
                .eq("del_flag", "0")
                .lt("repayment_time", DateUtils.parseDateToStr("yyyy-MM-dd", new Date()))
        );
        if (CollectionUtil.isNotEmpty(list)) {
            for (ApplyEntity entity : list) {
                if (entity.getStatus().equals("6")) {
                    entity.setStatus("8");
                }
                int days = DateUtils.differentDaysByMillisecond(new Date(), DateUtils.parseDate(entity.getRepaymentTime()));
                entity.setOverDay(days);
                //计算逾期费用
                Integer money = Integer.valueOf(entity.getExpireRate() * entity.getRealApplyMoney() / 100);
                entity.setOverMoney(entity.getOverMoney() + money);
                entity.setOverDay(days);
                applyMapper.updateById(entity);
                //添加逾期记录
                overLogService.save(entity, money);
            }
        }
    }

    /**
     * 增加待提现和催收记录
     *
     * @param params
     * @return
     */
    @Override
    public int addOverLogForm(JSONObject params) {
        Long id = params.getLong("id");
        String remark = params.getString("remark");
        String detail = params.getString("detail");
        ApplyEntity entity = applyMapper.selectById(id);
        if (entity.getStatus().equals("4")) {
            entity.setCustomerRemarkTime(new Date());
            entity.setCustomerRemark(detail);
            return applyMapper.updateById(entity);
        }
        entity.setRemark(remark);
        applyMapper.updateById(entity);
        return collectionLogService.save(entity, remark, detail);
    }

    @Override
    public List<CollectionLogEntity> overLogList(Long userId) {
        return collectionLogService.overLogList(userId);
    }

    private void queryPayOrderStatus(ApplyEntity entity) {
        //获取订单支付渠道
        if (entity.getCompanyId() != null) {
            CompanyEntity companyEntity = companyMapper.selectById(entity.getCompanyId());
            if (companyEntity != null && companyEntity.getStatus().equals("0") && companyEntity.getPayType().equals("0")) {
                if (companyEntity.getPayChannel() != null) {
                    PayConfigEntity payConfigEntity = payConfigMapper.selectById(companyEntity.getPayChannel());
                    if (payConfigEntity != null && payConfigEntity.getPayCompany().equals(PayCompanyEnum.ODD_PAY.getCode())) {
                        String result = VaUtils.queryOrderMd5(payConfigEntity.getAppId(), entity.getOrderSn());
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        if (jsonObject.getString("ret_code").equals("0000")) {
                            JSONObject retData = jsonObject.getJSONObject("ret_data");
                            String orderNo = retData.getString("order_no");
                            Integer amount = retData.getInteger("amount");
                            String status = retData.getString("status");
                            if (status.equals("02")) {
                                entity.setStatus("6");
                                //判断是否是白户
                                Long count = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", entity.getUserId()).eq("status", "7"));
                                if (count == 0) {
                                    entity.setWhiteUser("1");
                                } else {
                                    entity.setWhiteUser("0");
                                }
                                long systemNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", entity.getUserId()).in("status", "6", "7", "8"));
                                long agentNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", entity.getUserId()).in("status", "6", "7", "8").eq("company_id", entity.getCompanyId()));
                                entity.setAgentBorrowLevel(agentNum == 0 ? 1 : (int) (agentNum + 1));
                                entity.setSystemBorrowLevel(systemNum == 0 ? 1 : (int) (systemNum + 1));
                                entity.setApplyTime(new Date());
                                entity.setBankCardNo(retData.getString("tranId"));
                                Date date = DateUtils.addDays(new Date(), entity.getApplyCycle() - 1);
                                entity.setRepaymentTime(DateUtils.parseDateToStr("yyyy-MM-dd", date));
                                applyMapper.updateById(entity);
                                //添加打款记录
                                String bankOrderNo = retData.getString("charge_id");
                                payLogService.saveLogSuccess(entity, bankOrderNo);

                                UserBankEntity userBank = userBankService.getUserBank(entity.getUserId());
                                BankEntity bankEntity = bankService.selectById(userBank.getBankId());
                                Map params = new HashMap();
                                params.put("companyName", "(" + companyEntity.getName() + ")");
                                params.put("bankName", bankEntity.getSimpleName());
                                smsTemplateService.sendSms(StringUtils.checkPhone(entity.getUserPhone()), SmsTemplateType.PAY_SUCCESS.getCode(), params);
                            } else if (status.equals("03")) {
                                entity.setStatus("10");
                                applyMapper.updateById(entity);
                                payLogService.saveLogFail(entity, jsonObject.getString("ret_desc"));
                            }
                        } else if (jsonObject.getString("ret_code").equals("0002")) {
                            entity.setStatus("10");
                            applyMapper.updateById(entity);
                            payLogService.saveLogFail(entity, jsonObject.getString("ret_desc"));
                        }
                    }
                }
            }
        }
    }

    public void payApplyNew(ApplyEntity applyEntity) {
        //判断订单状态
        ApplyEntity entity = applyMapper.selectById(applyEntity.getId());
        if (entity.getStatus().equals("5")) {
            //打款金额
            Integer payMoney = applyEntity.getRealApplyMoney() - applyEntity.getManageMoney() - applyEntity.getRiskMoney() - applyEntity.getApplyServiceCharge();
            UserEntity userEntity = userService.selectUserById(applyEntity.getUserId());
            CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());

            if (companyEntity.getPayType().equals("0")) {
                //查询打款通道
                if (companyEntity.getPayChannel() != null) {
                    PayConfigEntity payConfigEntity = payConfigMapper.selectById(companyEntity.getPayChannel());
                    if (payConfigEntity != null && payConfigEntity.getPayCompany().equals(PayCompanyEnum.ODD_PAY.getCode())
                            && StringUtils.isNotBlank(payConfigEntity.getPayNotifyUrl())) {
                        oddPay(applyEntity, userEntity, payConfigEntity, String.valueOf(payMoney));
                    } else if (payConfigEntity != null && payConfigEntity.getPayCompany().equals(PayCompanyEnum.HQ_PAY.getCode())) {
                        //hqpay支付
                        hqpay(applyEntity, userEntity, payConfigEntity, payMoney, companyEntity.getName());
                    }
                }
            }
        }
    }

    /**
     * hqpay代付
     *
     * @param applyEntity
     * @param userEntity
     * @param payConfigEntity
     * @param payMoney
     */
    private void hqpay(ApplyEntity applyEntity, UserEntity userEntity, PayConfigEntity payConfigEntity, Integer payMoney, String companyName) {
        String payResult = "";
        String token = payConfigEntity.getHqpayToken();
        String msg = "";
        UserBankEntity userBank = userBankService.getUserBank(userEntity.getUserId());
        if (StringUtils.isBlank(token)) {
            try {
                String result = HQPayUtils.login(payConfigEntity.getMercharntId(), payConfigEntity.getAppId());
                JSONObject jsonObject = JSONObject.parseObject(result);
                String tokenType = jsonObject.getJSONObject("data").getString("token_type");
                String accessToken = jsonObject.getJSONObject("data").getString("access_token");
                if (StringUtils.isBlank(tokenType) || StringUtils.isBlank(accessToken)) {
                    log.error("hqpay登录获取token失败");
                    msg = "hqpay登录获取token失败";
                } else {
                    token = tokenType + " " + accessToken;
                    payConfigEntity.setHqpayToken(token);
                    payConfigMapper.updateById(payConfigEntity);
//                RedisUtils.setCacheObject(Constants.HQ_PAY_TOKEN + payConfigEntity.getId(), hqpayToken, expires, TimeUnit.SECONDS);

                    BankEntity bankEntity = bankService.selectById(userBank.getBankId());
                    if (userBank != null) {
                        if (StringUtils.isBlank(bankEntity.getHqpayBankId())) {
                            bankService.updateHqpayBankId();
                        }
                        bankEntity = bankService.selectById(userBank.getBankId());
                        payResult = HQPayUtils.pay(userBank.getBankNo(), userEntity.getUserName(), payMoney, bankEntity.getHqpayBankId(), applyEntity.getOrderSn(), companyName, token);
                    } else {
                        msg = "用户银行卡不存在";
                    }
                }
            } catch (Exception e) {
                log.error("支付异常：" + e.getMessage());
            }
        } else {
            try {
                BankEntity bankEntity = bankService.selectById(userBank.getBankId());
                if (userBank != null) {
                    if (StringUtils.isBlank(bankEntity.getHqpayBankId())) {
                        bankService.updateHqpayBankId();
                    }
                    bankEntity = bankService.selectById(userBank.getBankId());
                    payResult = HQPayUtils.pay(userBank.getBankNo(), userEntity.getUserName(), payMoney, bankEntity.getHqpayBankId(), applyEntity.getOrderSn(), companyName, token);
                }
            } catch (Exception e) {

            }
        }

        if (StringUtils.isNotBlank(payResult)) {
            JSONObject jsonObject = JSONObject.parseObject(payResult);
            if (jsonObject.getBoolean("success")) {
                if (jsonObject.getJSONObject("data").getBoolean("ok")) {
                    String orderNumber = jsonObject.getJSONObject("data").getString("order_number");
                    String amount = jsonObject.getJSONObject("data").getString("amount");
                    ApplyEntity entity = applyMapper.selectOne(new QueryWrapper<ApplyEntity>().eq("order_sn", orderNumber));
                    if (entity != null) {
                        entity.setStatus("6");
                        //判断是否是白户
                        Long count = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("status", "7").eq("user_id", entity.getUserId()));
                        long systemNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", entity.getUserId()).in("status", "6", "7", "8"));
                        long agentNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", entity.getUserId()).in("status", "6", "7", "8").eq("company_id", entity.getCompanyId()));
                        entity.setAgentBorrowLevel(agentNum == 0 ? 1 : (int) (agentNum + 1));
                        entity.setSystemBorrowLevel(systemNum == 0 ? 1 : (int) (systemNum + 1));
                        if (count == 0) {
                            entity.setWhiteUser("1");
                        } else {
                            entity.setWhiteUser("0");
                        }
                        applyEntity.setBankCardNo(userBank.getBankNo());
                        applyEntity.setSimpleName(userBank.getSimpleName());
                        entity.setApplyTime(new Date());
                        Date date = DateUtils.addDays(new Date(), applyEntity.getApplyCycle() - 1);
                        entity.setRepaymentTime(DateUtils.parseDateToStr("yyyy-MM-dd", date));
                        applyMapper.updateById(entity);
                        //添加打款记录
                        String refNum = jsonObject.getJSONObject("data").getString("merchant_requestId");
                        payLogService.saveLogSuccess(entity, refNum);
                        CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());

                        BankEntity bankEntity = bankService.selectById(userBank.getBankId());
                        Map params = new HashMap();
                        params.put("companyName", "(" + companyEntity.getName() + ")");
                        params.put("bankName", bankEntity.getSimpleName());
                        smsTemplateService.sendSms(StringUtils.checkPhone(applyEntity.getUserPhone()), SmsTemplateType.PAY_SUCCESS.getCode(), params);
                        //创建虚拟卡或虚拟账户
                        if (payConfigEntity.getVaType().equals("1")) {
                            String cardResult = HQPayUtils.createVirtualCard(token);
                            JSONObject cardJsonResult = JSONObject.parseObject(cardResult);
                            if (cardJsonResult.getBoolean("success")) {
                                JSONObject data = cardJsonResult.getJSONObject("data");
                                uservaService.saveUserVaHqpay(data, applyEntity, payConfigEntity);
                            }
                        } else {
                            try {
                                String cardResult = HQPayUtils.createNewVa(applyEntity.getOrderSn(), applyEntity.getUserName(), companyName, token);
                                JSONObject cardJsonResult = JSONObject.parseObject(cardResult);
                                if (cardJsonResult.getBoolean("ok")) {
                                    String batchId = cardJsonResult.getString("batch");
                                    JSONArray data = cardJsonResult.getJSONArray("accounts");
                                    String accounts = cardJsonResult.getString("accounts");
                                    List<AccountEntity> list = JSONObject.parseArray(accounts, AccountEntity.class);
                                    if (list.size() > 0) {
                                        uservaService.saveUserVaHqpayNew(list.get(0), applyEntity, payConfigEntity, batchId);
                                    }
                                }
                            } catch (Exception e) {
                                log.error("创建虚拟账户异常:" + e.getMessage());
                            }
                        }
                    }
                } else {
                    applyEntity.setStatus("10");
                    applyMapper.updateById(applyEntity);
                    String message = jsonObject.getString("message");
                    payLogService.saveLogFail(applyEntity, message);
                }
            } else {
                applyEntity.setStatus("10");
                applyMapper.updateById(applyEntity);
                String message = jsonObject.getString("message");
                payLogService.saveLogFail(applyEntity, message);
            }
        } else {
            applyEntity.setStatus("10");
            applyMapper.updateById(applyEntity);
            //添加打款记录
            payLogService.saveLogFail(applyEntity, msg);
        }
    }

    private void oddPay(ApplyEntity applyEntity, UserEntity userEntity, PayConfigEntity payConfigEntity, String payMoney) {
        //oddpay支付
        //查找用户银行卡信息
        try {
            UserBankEntity userBank = userBankService.getUserBank(userEntity.getUserId());
            if (userBank != null) {
                BankEntity bankEntity = bankService.selectById(userBank.getBankId());
                Map<String, Object> objectMap = VaUtils.payreq(payConfigEntity.getMercharntId(), payConfigEntity.getAppId(), payMoney,
                        applyEntity.getOrderSn(), userBank.getBankNo(), userEntity.getUserName(),
                        bankEntity.getBankNo(), bankEntity.getSimpleName(), "pay", payConfigEntity.getPayNotifyUrl());
                if (objectMap.get("ret_code").toString().equals("0000")) {
                    applyEntity.setStatus("6");
                    //判断是否是白户
                    Long count = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", applyEntity.getUserId()).eq("status", "7"));
                    if (count == 0) {
                        applyEntity.setWhiteUser("1");
                    } else {
                        applyEntity.setWhiteUser("0");
                    }
                    long agentNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", applyEntity.getUserId()).in("status", "6", "7", "8").eq("company_id", applyEntity.getCompanyId()));
                    long systemNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("user_id", applyEntity.getUserId()).in("status", "6", "7", "8"));
                    applyEntity.setSystemBorrowLevel(systemNum == 0 ? 1 : (int) (systemNum + 1));
                    applyEntity.setAgentBorrowLevel(agentNum == 0 ? 1 : (int) (agentNum + 1));
                    applyEntity.setApplyTime(new Date());
                    applyEntity.setBankCardNo(userBank.getBankNo());
                    applyEntity.setSimpleName(userBank.getSimpleName());
                    //应还时间
                    Date date = DateUtils.addDays(new Date(), applyEntity.getApplyCycle() - 1);
                    applyEntity.setRepaymentTime(DateUtils.parseDateToStr("yyyy-MM-dd", date));
                    applyMapper.updateById(applyEntity);
                    String retInfo = objectMap.get("ret_info").toString();
                    JSONObject jsonObject = JSONObject.parseObject(retInfo);
                    String bankOrderNo = jsonObject.getJSONObject("data").getJSONObject("result").getJSONObject("charge").getString("charge_id");
                    //增加打款记录
                    payLogService.saveLogSuccess(applyEntity, bankOrderNo);

                    CompanyEntity companyEntity = companyMapper.selectById(applyEntity.getCompanyId());
                    Map params = new HashMap();
                    params.put("companyName", "(" + companyEntity.getName() + ")");
                    params.put("bankName", bankEntity.getSimpleName());
                    smsTemplateService.sendSms(StringUtils.checkPhone(applyEntity.getUserPhone()), SmsTemplateType.PAY_SUCCESS.getCode(), params);

                    //创建虚拟卡
                    Map<String, Object> map = VaUtils.createVa(payConfigEntity.getMercharntId(), payConfigEntity.getAppId(), applyEntity.getOrderSn(),
                            String.valueOf(applyEntity.getRealApplyMoney()), DateUtils.parseDateToStr("yyyyMMdd", new Date()) + "000000",
                            DateUtils.parseDateToStr("yyyyMMdd", DateUtils.addWeeks(new Date(), 2)) + "235959",
                            userEntity.getUserName(), payConfigEntity.getVirtualNotifyUrl());
                    if (map != null && map.get("ret_code").equals("0000")) {
                        //创建虚拟卡
                        if (ObjectUtil.isNotNull(map.get("ret_data"))) {
                            uservaService.saveUserVa(map.get("ret_data").toString(), applyEntity, payConfigEntity);
                        }

                    }

                } else if (objectMap.get("ret_code").toString().equals("0005")) {
                    applyEntity.setStatus("10");
                    applyMapper.updateById(applyEntity);
                    String retInfo = objectMap.get("ret_info").toString();
                    JSONObject jsonObject = JSONObject.parseObject(retInfo);
                    String errorMsg = jsonObject.getString("retInfo");
                    payLogService.saveLogFail(applyEntity, errorMsg);
                } else {
                    applyEntity.setStatus("9");
                    applyMapper.updateById(applyEntity);
                    String retInfo = objectMap.get("ret_info").toString();
                    JSONObject jsonObject = JSONObject.parseObject(retInfo);
                    String errorMsg = jsonObject.getString("retInfo");
                    payLogService.saveLogWait(applyEntity, errorMsg);
                }
            }
        } catch (Exception e) {
            log.error("打款失败", e.getMessage());
            applyEntity.setStatus("10");
            applyMapper.updateById(applyEntity);
            //增加打款记录
            payLogService.saveLogFail(applyEntity, e.getMessage());
        }
    }

    /**
     * 还款
     *
     * @param applyId
     * @param type
     * @param paymentMoney
     * @param status       0 未结清   1 结清
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized int paymentApply(Long applyId, String type, Integer paymentMoney, String status) {
        int count = 0;
        boolean paymentFlag = false;
        if (type.equals("0")) {
            //线下还款
            //修改订单记录
            ApplyEntity applyEntity = applyMapper.selectById(applyId);
            Integer alreadyRepayMoney = applyEntity.getAlreadyRepayMoney();
            applyEntity.setAlreadyRepayMoney(alreadyRepayMoney + paymentMoney);
            if (applyEntity.getAlreadyRepayMoney() >= (applyEntity.getRealApplyMoney() + applyEntity.getInterestMoney() + applyEntity.getOverMoney())) {
                if (status.equals("1")) {
                    applyEntity.setBalancerBy(LoginHelper.getUserId());
                    applyEntity.setStatus("7");
                    //判断是否绑定催收用户
                    if (ObjectUtil.isNotNull(applyEntity.getCollectionBy())) {
                        CollectionOrderHandleEntity collectionOrderHandleEntity = collectionOrderHandleService.selectByApply(applyEntity);
                        if (ObjectUtil.isNotNull(collectionOrderHandleEntity)) {
                            collectionOrderHandleEntity.setCallbackAmount(collectionOrderHandleEntity.getCallbackAmount() + paymentMoney);
                            if (DateUtils.parseDate(applyEntity.getRepaymentTime()).before(new Date())) {
                                collectionOrderHandleEntity.setStatus("timeout_all_collect_end");
                            } else {
                                collectionOrderHandleEntity.setStatus("success");
                            }
                            collectionOrderHandleEntity.setUpdateTime(new Date());
                            collectionOrderHandleService.update(collectionOrderHandleEntity);
                        }
                    }
                }
                applyEntity.setAlreadyRepayTime(new Date());
                paymentFlag = true;
            } else {
                if (status.equals("1")) {
                    applyEntity.setBalancerBy(LoginHelper.getUserId());
                    applyEntity.setStatus("7");
                    applyEntity.setAlreadyRepayTime(new Date());
                    paymentFlag = true;
                    if (ObjectUtil.isNotNull(applyEntity.getCollectionBy())) {
                        CollectionOrderHandleEntity collectionOrderHandleEntity = collectionOrderHandleService.selectByApply(applyEntity);
                        if (ObjectUtil.isNotNull(collectionOrderHandleEntity)) {
                            collectionOrderHandleEntity.setCallbackAmount(collectionOrderHandleEntity.getCallbackAmount() + paymentMoney);
                            if (DateUtils.parseDate(applyEntity.getRepaymentTime()).before(new Date())) {
                                collectionOrderHandleEntity.setStatus("timeout_part_collect_end");
                            } else {
                                collectionOrderHandleEntity.setStatus("success");
                            }
                            collectionOrderHandleEntity.setUpdateTime(new Date());
                            collectionOrderHandleService.update(collectionOrderHandleEntity);
                        }
                    }
                } else {
                    if (ObjectUtil.isNotNull(applyEntity.getCollectionBy())) {
                        CollectionOrderHandleEntity collectionOrderHandleEntity = collectionOrderHandleService.selectByApply(applyEntity);
                        if (ObjectUtil.isNotNull(collectionOrderHandleEntity)) {
                            collectionOrderHandleEntity.setCallbackAmount(collectionOrderHandleEntity.getCallbackAmount() + paymentMoney);
                            collectionOrderHandleEntity.setUpdateTime(new Date());
                            collectionOrderHandleService.update(collectionOrderHandleEntity);
                        }
                    }
                }
            }
            count = applyMapper.updateById(applyEntity);
            //添加还款记录
            repaymentLogService.savePaymentLog(applyEntity, type, paymentMoney, null, null);
            //如果最终还款成功,则给所有在线的公司生成待终审订单
            if (paymentFlag) {
                saveTwoExamineApply(applyEntity);
            }

        } else if (type.equals("1")) {
            //线上还款
        }
        return count;
    }

    /**
     * 给所有公司生成待终审订单
     *
     * @param applyEntity
     */
    private void saveTwoExamineApply(ApplyEntity applyEntity) {
        List<CompanyEntity> companyEntityList = companyMapper.selectList(new QueryWrapper<CompanyEntity>().eq("status", "0").eq("del_flag", "0"));
        if (!CollectionUtils.isEmpty(companyEntityList)) {
            for (CompanyEntity companyEntity : companyEntityList) {
                //判断该用户在该公司是否有未处理完的订单
                ApplyEntity entity = applyMapper.selectOne(new QueryWrapper<ApplyEntity>()
                        .eq("user_id", applyEntity.getUserId())
                        .eq("del_flag", "0")
                        .eq("company_id", companyEntity.getId())
                        .ne("status", "7")
                );
                //判断用户在该公司是否有还款成功的订单，如果有就是复借
                long count = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                        .eq("user_id", applyEntity.getUserId())
                        .eq("del_flag", "0")
                        .eq("company_id", companyEntity.getId())
                        .eq("status", "7")
                );
                if (ObjectUtil.isNull(entity)) {
                    entity = new ApplyEntity();
                    entity.setApplyNum((int) (count + 1));
                    entity.setCompanyId(companyEntity.getId());
                    entity.setUserId(applyEntity.getUserId());
                    entity.setUserName(applyEntity.getUserName());
                    entity.setUserPhone(applyEntity.getUserPhone());
                    entity.setOrderSn(StringUtils.getOrderNumNew(applyEntity.getUserId()));
                    entity.setApplyMoney(applyEntity.getRealApplyMoney());
                    entity.setStatus("999");
                    entity.setIpAddress(applyEntity.getIpAddress());
                    entity.setIdCardNumber(applyEntity.getIdCardNumber());
                    entity.setAgentBorrowLevel(applyEntity.getAgentBorrowLevel() + 1);
                    entity.setSystemBorrowLevel(applyEntity.getSystemBorrowLevel() + 1);
                    entity.setChannel(applyEntity.getChannel());
                    if (count > 0) {
                        entity.setFirstApply("2");
                    }
                    applyMapper.insert(entity);
                }
            }
        }
    }

    /**
     * 计算每日利息
     */
    @Override
    public void calculationApplyInterestByDay() {
        List<ApplyEntity> list = applyMapper.selectList(new QueryWrapper<ApplyEntity>()
                .eq("status", "6")
                .eq("del_flag", "0")
        );
        if (!CollectionUtils.isEmpty(list)) {
            for (ApplyEntity entity : list) {
                Integer dayRate = entity.getDayRate();
                Integer realApplyMoney = entity.getRealApplyMoney();
                Integer money = dayRate * realApplyMoney;
                Integer interestMoney = entity.getInterestMoney();
                entity.setInterestMoney(interestMoney + (money / 100));
                applyMapper.updateById(entity);
            }
        }
    }


    private Wrapper<ApplyEntity> buildQueryWrapper(ApplyEntity entity, Integer applyType, String isDivide,String isRemark) {
        Map<String, Object> params = entity.getParams();
        QueryWrapper<ApplyEntity> wrapper = Wrappers.query();
        Long userId = LoginHelper.getUserId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (applyType != null) {
            applyType++;
        }
//        if (ObjectUtil.isNotNull(entity.get))
        wrapper.like(StringUtils.isNotBlank(entity.getUserName()), "a.user_name", entity.getUserName())
                .like(StringUtils.isNotBlank(entity.getUserPhone()), "a.user_phone", entity.getUserPhone())
                .like(StringUtils.isNotBlank(entity.getOrderSn()), "a.order_sn", entity.getOrderSn())
                .eq(ObjectUtil.isNotNull(entity.getUserId()), "a.user_id", entity.getUserId())
                .eq(ObjectUtil.isNotNull(entity.getApplyCycle()), "a.apply_cycle", entity.getApplyCycle())
                .eq(ObjectUtil.isNotNull(sysUser.getCompanyId()), "a.company_id", entity.getCompanyId())
                .eq(StringUtils.isNotBlank(entity.getStatus()), "a.status", entity.getStatus())
                .eq(ObjectUtil.isNotNull(entity.getCompanyId()), "a.company_id", entity.getCompanyId())
                .eq(ObjectUtil.isNotNull(entity.getOneExamineBy()), "a.one_examine_by", entity.getOneExamineBy())
                .eq(ObjectUtil.isNotNull(entity.getTwoExamineBy()), "a.two_examine_by", entity.getTwoExamineBy())
                .eq(ObjectUtil.isNotNull(entity.getCustomerBy()), "a.customer_by", entity.getCustomerBy())
                .isNull(StringUtils.isNotBlank(isDivide) && isDivide.equals("1"), "a.customer_by")
                .isNotNull(StringUtils.isNotBlank(isDivide) && isDivide.equals("2"), "a.customer_by")
                .eq(StringUtils.isNotBlank(isRemark)&& "0".equals(isRemark), "a.customer_remark", "")
                .ne(StringUtils.isNotBlank(isRemark)&& "1".equals(isRemark), "a.customer_remark", "")
                .eq(applyType != null, "apply_num", applyType)
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "a.customer_create_time", DateUtils.toBeginDateByDay(params.get("beginTime")), DateUtils.toEndDateByDay(params.get("endTime")))
                .orderByDesc("a.id");
        return wrapper;
    }
}
